<template>
  <div class="box">
    <div class="box-header">{{ year }}年度账单</div>
    <div class="box-body" id="charts1"></div>
  </div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { onMounted, computed, ref, reactive } from 'vue'
// 接受父组件数据
const prop = defineProps({
  data: { type: Array, default: [] },
})
const year = ref('2025')
const xdata = ref<any>([])
const series = ref<any>([])
const initData = (()=>{
  const arr = ['01','02','03','04','05','06','07','08','09','10','11','12']
  const obj = {}
  arr.forEach(item=>{
      const monthNum = parseInt(item);
      obj[`${monthNum}月`] = [];
      prop.data.forEach(item2=>{
        let time =item2.time.slice(0,7)
        if(`${year.value}-${item}`===time){
             obj[`${monthNum}月`].push(item2.price)
        }
      })
  })
  const monthlySum = {};
  for (const month in obj) {
    const sum = obj[month].reduce((total, num) => total + parseFloat(num), 0);
    monthlySum[month] =  Math.round(sum * 100) / 100; // 四舍五入保留2位小数
  }
  xdata.value = Object.keys(monthlySum)
  series.value = Object.values(monthlySum)
})
const initChart = () => { 
  var myChart = echarts.init(document.getElementById('charts1'));
  // 绘制图表
  myChart.setOption({
    tooltip: {},
    xAxis: {
      data: xdata.value
    },
    yAxis: {
      type: 'value',
      name: '金额(元)',
      show: true
    },
    series: [
      {
        name: '金额',
        type: 'bar',
        label: {
          show: true,
          position: 'top'
        },
        data: series.value
      }
    ]
  });
}
onMounted(()=>{
  initData()
  initChart()
})
</script>
<style scoped lang="scss">
.box{
width: 100%;
height: 100%;
.box-header{
    width: 100%;
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    text-align: center;
}
.box-body{
  width: 100%;
  height: calc(100% - 50px);
  background: #fff;
}
}
</style>
